package com.hao.elasticsearch.utils;

import com.hao.elasticsearch.entity.Content;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;
import sun.nio.cs.ext.GBK;

import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: 苦逼程序员
 **/
@Component
public class HtmlPaseUtils {

    public List<Content> paseJD(String keyword) throws Exception {
        //获取请求 http://search.jd.com/Search?keyword=java
        //前提，需要联网

        String url = "http://search.jd.com/Search?keyword=" + keyword;
        //解析网页 jsoup返回的document就是js的document对象
        Document document = Jsoup.parse(new URL(url),30000 );
        //所有你在js中使用的方法这里都有
        Element element = document.getElementById("J_goodsList");
//        System.out.println(element.html());
        //获取网页所有的li元素
        Elements li = element.getElementsByTag("li");

        List<Content> list = new ArrayList<Content>();

        //遍历li元素中的内容
        for (Element el : li
        ) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String title = el.getElementsByClass("p-name").eq(0).text();

            list.add(new Content(img, title, price));
        }

        return list;
    }
}
